using UnityEditor;
using UnityEngine;

namespace Gameplay.PVE.Editor
{
    public class EditorAnimPlayer
    {
        public void Initialize(Animator obj)
        {
            animator = obj;
        }
        
        public void Initialize(GameObject obj)
        {
            animator = obj.GetComponentInChildren<Animator>();
        }
        
        private bool isPlaying = false;
        private string currentPlayingAnim = string.Empty;

        private double m_CurTime;
        private double m_PreviousTime;

        private const float kDuration = 100;
        private float m_RunningTime;
        private float m_RecorderStopTime;

        private Animator animator;
        
        
        
        public void Play(string name)
        {
            //if (name != currentPlayingAnim)
            {
                isPlaying = true;
                //animator?.SetTrigger(action.actionName);
                m_RunningTime = 0;
                bake(name);
                currentPlayingAnim = name;
            }
        }
        
        private  void bake(string name)
        {
            if (Application.isPlaying || animator ==  null)
            {
                return;
            }

            const  float frameRate = 30f;
            const  int frameCount = ( int)((kDuration * frameRate) +  2);
            if (currentPlayingAnim != string.Empty)
            {
                animator.ResetTrigger(currentPlayingAnim);
            }

            animator.Rebind();
            animator.Play(name);
            animator.StopPlayback();
            animator.recorderStartTime =  0;

            // 开始记录指定的帧数
            animator.StartRecording(frameCount);

            for (var i =  0; i < frameCount -  1; i++)
            {
          
                // 记录每一帧
                animator.Update( 1.0f / frameRate);
            }
            // 完成记录
            animator.StopRecording();

            // 开启回放模式
            animator.StartPlayback();
            m_RunningTime = 0;
            m_RecorderStopTime = animator.recorderStopTime;
        }
        
        private  void UpdateAnimator()
        {
            if (Application.isPlaying || animator ==  null)
            {
                return;
            }
            if (m_RunningTime > m_RecorderStopTime)
            {
                currentPlayingAnim = string.Empty;
                return;
            }
    
          
            // 设置回放的时间位置
            animator.playbackTime = (float)m_RunningTime;
            animator.Update( 0);
            m_CurTime = m_RunningTime;
        }
        
        public void Update(double delta)
        {
            if (isPlaying)
            {
                m_RunningTime = Mathf.Clamp(m_RunningTime + ( float)delta, 0f, kDuration);
                UpdateAnimator();
            }
        }

        public void Update(float runningTime)
        {
            m_RunningTime = runningTime;
            UpdateAnimator();
        }

    }
}